<?php

namespace App\Repositories\Admin;

use App\BaseRepository;
use App\Model\ArticleResource;
use App\Model\Resource;
use App\Model\ResourceTable;
use Illuminate\Support\Facades\DB;

class ArticleRepository extends BaseRepository
{
    protected $modelName = "App\Model\Article";

    protected function query()
    {
        return $this->model()->where('column_id','<>',1);
    }

    //列表页load其他关联数据
    protected function relationLoad()
    {
        return ['column'];
    }

    protected function beforeListShow($model)
    {
        return $model->orderBy('weight','desc')->orderBy('created_at','desc')
            ->select('id','title','author','online','weight','pv','uv','collection_quantity','created_at','updated_at','column_id');
    }

    //格式化show显示的数据
    protected function getShowRespondData($model)
    {
        return $model->load('column','covers');
    }

    protected function commonRules()
    {
        return [
            'title' => 'required',
            'author' => 'required',
            'column_id' => 'required',
            'abstract' => 'required',
            'type' => 'required|in:article,video',
            'video_type' =>'required_if:type,video',
            'video_path' =>'required_if:type,video',
            'content' => 'required_if:type,article',
            //'state' => 'required|in:publish,draft'
        ];
    }

    //保存封面 cover_ids
    private function saveCovers($model)
    {
        if ($this->request->exists('cover_ids')) {
            $ids = $this->request->input('cover_ids');

            $rows = $ids?explode(',',$ids) : [];

            $db = DB::table('sys_resource_table')->where('obj_id','=',$model->id)
                ->where('obj_type','=','article_cover');

            $o_ids = $db->pluck('resource_id')->toArray();

            $db->whereIn('resource_id',array_diff($o_ids,$rows))->delete();

            $rows = array_diff($rows,$o_ids);

            foreach ($rows as $row) {
                $AR = new ResourceTable();
                $AR->obj_id = $model->id;
                $AR->resource_id = $row;
                $AR->user_id = $this->loginUser->id;
                $AR->obj_type = 'article_cover';
                $AR->save();
            }
            return true;
        }
        return false;
    }

    protected function commonSave($model)
    {
        return $this->saveCovers($model);
    }

    //获取保存到数据库的数据
    protected function getStoreFillData()
    {
        $data = $this->removeNullFromArray($this->request->all());
        return array_merge($data,['user_id'=>$this->loginUser->id,'state'=>'publish','online'=>'no']);
    }

    protected function destroyValidate($id)
    {
        $c = DB::table('wine_focus_picture')->where('obj_id','=',$id)->where('type','=','article')
            ->whereNull('deleted_at')->count();

        if($c>0) {
            $this->error = "此文章已关联焦点图";
            return false;
        }
        return true;
    }
}
